
import socket
import sys, struct
import thread

#http_response = "HTTP/1.1 200 OK\r\nContent-Type: text/html;charset=utf-8\r\nContent-Length:12\r\n\r\nHello, World!"
http_response = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length:42\r\n\r\n<html><meta charset=\"UTF-8\"/>Hello!</html>"
server_close_url = "server-close.html"
http_server_close_response = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n<html><meta charset=\"UTF-8\"/>Hello server close test!</html>"

def Usage():
    print("python ./name <ip> <port>")

receive_allflag = 0
def client_socket_process(client_connection):
    while True:
        request = []
        try:
            if receive_allflag:
                val = struct.pack("QQ", 1, 50000)
                client_connection.setsockopt(socket.SOL_SOCKET, socket.SO_RCVTIMEO, val)
            while True:
                request1 = client_connection.recv(10240)
                print(request1)
                if not request1: break
                request.append(request1)
                if receive_allflag == 0:
                    break

        except Exception as e:
            print("receive exception:" + str(e))

        if len(request) == 0:
            client_connection.close()
            break

        if server_close_url in request[:128]:
            client_connection.sendall(http_server_close_response.encode())
            print("send server-close response %s" % (http_server_close_response))
            client_connection.close()
            break
        else:
            client_connection.sendall(http_response.encode())
            print("send response %s" % (http_response))
            
   

if __name__ == "__main__":
    if len(sys.argv) < 3:
        Usage()
        exit()

    HOST = sys.argv[1]
    PORT = int(sys.argv[2])
    if len(sys.argv) == 4:
        receive_allflag = int(sys.argv[3])

    listen_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    listen_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    listen_socket.bind((HOST, PORT))
    listen_socket.listen(1)
    print('Serving HTTP on host %s port %s ...' %(HOST, PORT))
    while True:
        client_connection, client_address = listen_socket.accept()
        thread.start_new_thread(client_socket_process, (client_connection,))

